const Router = require("@koa/router");
const router = new Router();
const { modelDairecom } = require("@/models/dailyrecom");
const { modelFourTravel } = require("@/models/fourtravel");
const { modelHomeTab } = require("@/models/hometab");
const moment = require("moment");
moment.locale("zh-cn");
const fs = require("fs");
const path = require("path");
const { looKup, looKupRecommend } = require("@/config/lookup");
const { Resreturn, Clssifytravels } = require("@/validData/home");
const { modelArticle } = require("@/models/article");
const { Auth } = require("@/token/auth");
const { modelLike } = require("@/models/like");
const { modelConcern } = require("@/models/concern");
const { modelCollection } = require("@/models/collection");

// 获取小程序顶部每日推荐游记
router.get("/wxGainDailyRecom", async (ctx) => {
  const { page } = ctx.request.query;
  Resreturn(page);
  const res = await modelDairecom
    .find(
      {},
      {
        time: false,
        timestamp: false,
      }
    )
    .sort({ timestamp: -1 })
    .skip((page - 1) * 1)
    .limit(1);
  // 获取总条数
  const count = await modelDairecom.countDocuments();
  const resObj = {
    data: res,
    count,
  };
  ctx.send("SUCCESS", 200, resObj);
});

// 获取小程序端四个游记推荐
router.get("/wxGainRecomTravel", async (ctx) => {
  const res = await modelFourTravel.aggregate([
    { $sort: { timestamp: -1 } },
    looKupRecommend().model_Article,
    looKupRecommend().model_reco_user,
    { $unwind: "$articleData" },
    { $unwind: "$userData" },
    {
      $project: {
        _id: 1,
        imageUrl: 1,
        travel_id: 1,
        title: "$articleData.title",
        address: "$articleData.address",
        fileType: "$articleData.fileType",
        nickname: "$userData.nickname",
        avatarUrl: "$userData.avatarUrl",
      },
    },
  ]);
  ctx.send("SUCCESS", 200, res);
});

// 获取小程序端10个游记分类
router.get("/recomm-travel", async (ctx) => {
  const res = await modelHomeTab.find({});
  ctx.send("SUCCESS", 200, res);
});

// 导入10个游记分类到数据库
router.get("/hometab-database", async (ctx) => {
  // return false;
  const citydata = JSON.parse(
    fs.readFileSync(path.join(process.cwd(), "hometab.json"), "utf8")
  );
  await modelHomeTab.insertMany(citydata);
  ctx.send("SUCCESS", 200, { message: "导入成功" });
});

// 游记分类切换tab
router.get("/travelogue-class", async (ctx) => {
  const res = moment().utcOffset(8).format("M");
  const arr = [
    { name: "推荐", key: "001" },
    { name: `${res}月去哪`, key: "002" },
    { name: "露营", key: "003" },
    { name: "古镇漫游", key: "004" },
    { name: "徒步骑行", key: "005" },
    { name: "躺酒店", key: "006" },
    { name: "宝藏小城", key: "007" },
    { name: "亲子游", key: "008" },
    { name: "博物馆", key: "009" },
    { name: "摄影", key: "010" },
    { name: "海景", key: "011" },
  ];
  ctx.send("SUCCESS", 200, arr);
});

// 获取首页瀑布流游记
router.get("/user-travels", async (ctx) => {
  const { keywords, page } = ctx.query;
  Clssifytravels(keywords, page);
  let match = {};
  if (keywords === "001") {
    match = {};
  } else if (keywords === "002") {
    // 取当前月份月初和月末的时间戳
    const startOfMonth = moment().clone().startOf("month").unix();
    const endOfMonth = moment().clone().endOf("month").unix();
    match = {
      time_stamp: {
        $gte: startOfMonth,
        $lte: endOfMonth,
      },
    };
  } else {
    const arr = [
      { name: "露营", key: "003" },
      { name: "古镇漫游", key: "004" },
      { name: "徒步骑行", key: "005" },
      { name: "躺酒店", key: "006" },
      { name: "宝藏小城", key: "007" },
      { name: "亲子游", key: "008" },
      { name: "博物馆", key: "009" },
      { name: "摄影", key: "010" },
      { name: "海景", key: "011" },
    ];
    const result = arr.filter((item) => item.key === keywords);
    match = {
      tag: { $in: [result[0].name] },
    };
  }
  const res = await modelArticle.aggregate([
    { $match: match },
    { $sort: { time_stamp: -1 } },
    { $skip: (page - 1) * 6 },
    { $limit: 6 },
    looKup().model_user,
    looKup().model_like,
    looKup().project,
  ]);
  ctx.send("SUCCESS", 200, res);
});

// 登录校验
router.get("/check-login", new Auth().m, async (ctx) => {
  ctx.send();
});

// 获取用户的点赞，关注，粉丝数量
router.get("/my-related", new Auth().m, async (ctx) => {
  // 我收到的点赞数量
  const likeCount = await modelLike
    .find({
      author_uid: ctx.auth.uid,
    })
    .countDocuments();
  // 我关注的数量
  const concernCount = await modelConcern
    .find({
      user_uid: ctx.auth.uid,
    })
    .countDocuments();
  // 我的粉丝数量
  const fansCount = await modelConcern
    .find({
      im_concerned_uid: ctx.auth.uid,
    })
    .countDocuments();

  ctx.send("SUCCESS", 200, {
    likeCount,
    concernCount,
    fansCount,
  });
});

// 查用户发布的游记
router.get("/myTravEls", new Auth().m, async (ctx) => {
  const { page } = ctx.query;
  Resreturn(page);
  const res = await modelArticle
    .find({
      author_uid: ctx.auth.uid,
    })
    .sort({ time_stamp: -1 })
    .skip((page - 1) * 6)
    .limit(6)
    .select("cover_image address fileType");
  ctx.send("SUCCESS", 200, res);
});

// 查询用户收藏的游记
router.get("/myCollEction", new Auth().m, async (ctx) => {
  const { page } = ctx.query;
  Resreturn(page);
  const articleId = await modelCollection.find(
    {
      user_uid: ctx.auth.uid,
    },
    {
      article_id: true,
    }
  );
  const resId = await articleId.map((item) => item.article_id);
  const res = await modelArticle.aggregate([
    { $match: { _id: { $in: resId } } }, //数组形式匹配游记表的_id
    { $sort: { time_stamp: -1 } },
    { $skip: (page - 1) * 6 },
    { $limit: 6 },
    {
      $project: {
        _id: 1,
        address: 1,
        fileType: 1,
        cover_image: 1,
      },
    },
  ]);
  ctx.send("SUCCESS", 200, res);
});

// 查询用户点赞的游记
router.get("/myLikeArticle", new Auth().m, async (ctx) => {
  const { page } = ctx.query;
  Resreturn(page);
  const articleId = await modelLike.find(
    {
      user_uid: ctx.auth.uid,
    },
    {
      article_id: true,
    }
  );
  const resId = await articleId.map((item) => item.article_id);
  const res = await modelArticle.aggregate([
    { $match: { _id: { $in: resId } } }, //数组形式匹配游记表的_id
    { $sort: { time_stamp: -1 } },
    { $skip: (page - 1) * 6 },
    { $limit: 6 },
    {
      $project: {
        _id: 1,
        address: 1,
        fileType: 1,
        cover_image: 1,
      },
    },
  ]);
  ctx.send("SUCCESS", 200, res);
});

// 根据游记分类关键词查询游记
router.get("/clAssifyTravels", async (ctx) => {
  const { keywords, page } = ctx.query;
  Clssifytravels(keywords, page);
  const query = { $regex: keywords, $options: "i" };
  const res = await modelArticle.aggregate([
    {
      $match: {
        $or: [
          { title: query },
          { content: query },
          { tag: { $in: [keywords] } },
        ],
      },
    },
    { $skip: (page - 1) * 6 },
    { $limit: 6 },
    looKup().model_user,
    looKup().model_like,
    looKup().project,
  ]);
  ctx.send("SUCCESS", 200, res);
});

module.exports = router.routes();
